<!--  -->
<template>
  <div class='courseApply' style="padding:20px">
    <!-- {{gabbageList.length && gabbageList.map(it=>it.imgSrc)}} -->
    <div v-if='$route.path != "/exper/views/teacher/courseApply"'>
      <!-- <el-page-header @back='$router.push(originPath)' content=''></el-page-header> -->
      <el-button type="primary" @click="$router.push(originPath)">返回</el-button>
    </div>
    <div>
      <div class="titleLine">课程基本信息</div>
      <el-form :model="baseInfoForm" ref="baseInfoForm" label-width="180px" :rules='baseInfoFormRule'>
        <el-card style="margin-top:-10px">
        <el-form-item label="课程名称" prop='courseName'>
          <el-input v-model="baseInfoForm.courseName" placeholder="课程名称" :disabled="isCheck"></el-input>
        </el-form-item>
        <el-form-item label="课程方向" prop='courseType'>
          <el-select v-model="baseInfoForm.courseType" placeholder="课程方向" :disabled="isCheck">
            <el-option v-for="opt in courseTypeList" :key="opt.type" :label="opt.name" :value="opt.type" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程难度">
          <el-select v-model="baseInfoForm.difficulty" placeholder="课程难度" :disabled="isCheck">
            <el-option v-for="opt in difficultyList" :key="opt.id" :label="opt.label" :value="opt.id" />
          </el-select>
        </el-form-item>
        <div style="display:flex">
          <el-form-item label="课程计划开始时间" prop='startTime'>
            <el-date-picker :disabled="isCheck" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOption" format="yyyy-MM-dd HH:mm:ss" v-model="baseInfoForm.startTime" type="datetime" placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="课程计划结束时间" prop='endTime'>
            <el-date-picker :disabled="isCheck" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions" format="yyyy-MM-dd HH:mm:ss" v-model="baseInfoForm.endTime" type="datetime" placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </div>
        </el-card>
        <div class="titleLine">课程介绍</div>
        <div class="titleWeight">课程封面上传</div>
        <el-form-item prop='homePage' >
          <el-upload :disabled="isCheck" class="avatar-uploader" ref="upload" action="#" :on-change="handleChange" :on-remove="handleRemove" :file-list="fileList" :auto-upload="false">
            <el-image v-if='baseInfoForm.homePage' :src="host +baseInfoForm.homePage" style="width:178px; height:178px"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon" style="font-size: 40px;margin:0;color: gray"></i>
          </el-upload>
        </el-form-item>
        <div class="titleWeight"> 课程概述</div>
        <el-input class="textAreaBox" type="textarea" :rows="5" v-model="baseInfoForm.overview" :disabled="isCheck"></el-input>
        <div class="titleWeight">课程目的</div>
        <el-input class="textAreaBox" type="textarea" :rows="5" v-model="baseInfoForm.purpost" :disabled="isCheck"></el-input>
        <div class="titleLine">课程资源</div>
        <img src="../overview/image/u69.jpg" alt="">
        <div class="titleLine">预习资料</div>
        <div class="titleWeight">预习资料介绍</div>
        <el-input class="textAreaBox" type="textarea" :rows="5" v-model="baseInfoForm.preDataContent" :disabled="isCheck"></el-input>
        <div style='margin: 20px auto 80px 20px'>
          <el-button type="primary" @click="onSubmit('save')" v-if='!isCheck' :disabled="isDisable" >{{courseId?'更新以上内容':'保存以上内容'}}</el-button>
        </div>
        <div class="titleWeight" v-show="isShow || courseId">预习资料上传</div>
        <el-form-item v-show="isShow || courseId">
          <el-upload v-if='!isCheck' :disabled="!courseId || isCheck" class="avatar-uploader" ref="upload" action="#" :on-change="handleChangePre" :show-file-list='false' :before-upload="handleBeforeUploadPre" :on-remove="handleRemovePre" :file-list="preList" :auto-upload="false" :before-remove='beforeRemove'>
            <i class="el-icon-plus avatar-uploader-icon"  style="font-size: 40px;margin:0;color: gray"></i>
          </el-upload>
          <div v-if='!courseId'>请添加课程后再上传资料</div>
          <div v-show='!isCheck' v-for='it in preList' @click='deleteFile(it)' :key='it.id' style="cursor:pointer">{{it.fileName}}
            <i class="el-icon-delete"></i>
          </div>
          <div v-if='isCheck' v-for='it in preList' @click='downLoadFile(it)' :key='it.id' style="cursor:pointer">{{it.fileName}}
            <i class="el-icon-download iconOperate"></i>
          </div>
        </el-form-item>
      </el-form>
      <div class="titleLine" v-show="isShow || courseId">课程大纲</div>

      <div class="custom-tree-container" v-show="isShow ||courseId">
        <div class="block" style="margin-left: 20px;">
          <div style="cursor:pointer; margin-bottom:10px;" v-if='!isCheck'>
            <el-button type="primary" :disabled="isDisable" @click="handleNewMoudle">新建章节</el-button>
          </div>
          <el-tree :data="data" node-key="id" :expand-on-click-node="false" @node-click="myEvent" default-expand-all>
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span v-if="!data.isEdit ">{{ node.label }}</span>
              <span class="isEdit" v-if='!isCheck'>
                <!-- 编辑状态 -->
                <div v-if="data.isEdit">
                  <!-- <el-input v-model="data.label" autofocus size="mini" :ref="'slotTreeInput' + data[id]" @blur.stop="handleInput(node, data)" @keyup.enter.native="handleInput(node, data)"></el-input> -->
                  <el-input v-model="data.label" autofocus size="mini" ref="slotTreeInput" @blur.stop="handleInput(node, data)" @keyup.enter.native="handleInput(node, data)"></el-input>
                </div>
                <div style="margin-left:50px;flex:4">
                  <el-button type="text" @click="() => append(node, data)" class="handleBtn">
                    <i class="el-icon-circle-plus-outline"></i>新增子章节</el-button>
                  <el-button type="text" @click="() => handleEdit(node, data)" class="handleBtn">
                    <i class="el-icon-edit"></i>编辑</el-button>
                  <el-button type="text" @click="() => remove(node, data)" class="handleBtn">
                    <i class="el-icon-delete"></i>删除</el-button>
                  <!-- <span @click="handleEdit(node, data)"  class="handleBtn">
                    <i class="el-icon-edit"></i>编辑</span> -->
                  <!-- <span @click="() => remove(node, data)"  class="handleBtn">
                    <i class="el-icon-delete"></i>
                    删除
                  </span> -->
                </div>
              </span>
            </span>
          </el-tree>
        </div>
      </div>
      <div style="margin-top:30px;padding-bottom:10px;text-align: center;">
        <!-- <el-button>保存 0</el-button> -->
        <el-button @click="onSubmit('submit')" v-if='!isCheck && (isShow || courseId)' :disabled="isDisable" type='primary'>提交审核</el-button>
        <el-button @click="check(1)" v-if='isCheck && !alreadyCheck && !isHandleSuccess' type='primary'>通过</el-button>
        <el-button @click="check(2)" v-if='isCheck && !alreadyCheck && !isHandleSuccess' type='danger'>驳回</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import teacherApi from "../api/teacher.service.js";
import operateApi from "../api/operate.service.js";

let id = 2;
var numtoCh = {};
export default {
  components: {},
  data() {
    return {
      baseInfoForm: {
        courseName: "", //课程名称
        difficulty: "", //课程难度
        startTime: "", //开始时间
        endTime: "", // 结束时间
        overview: "", //概述
        purpost: "", // 目的
        preDataContent: "", // 预习资料介绍
        courseType: "", // 当前页面所在模块是威胁还是数据汇集等
        homePage: "", //封面上传地址,
        homeName: "",
        preDataPath: "", //预习资料上传地址
      },
      data: [],
      id: "id", // id对应字段
      MAX_LEVEL: 3, // 设定最大层级,
      difficultyList: [], //课程级别
      courseId: "", //添加成功之后的cousreId， 添加大纲的时候需要
      fileList: [], //封面
      preList: [], //预习资料上传列表
      courseTypeList: [], //课程方向下拉框数组
      baseInfoFormRule: {
        courseType: [
          { required: true, message: "请选择课程方向", trigger: "change" },
        ],
        courseName: [
          { required: true, message: "课程名称不能为空", trigger: "change" },
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "change" },
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "change" },
        ],
      },
      homePng: "",
      originPath: "",
      isCheck: false, //是否是从课程审核过来，这样只能查看
      host: window.location.href.split("/#/")[0] + "/api",
      alreadyCheck: false,
      pickerOption: this.startDate(),
      pickerOptions: this.endDate(),
      isShow: false, // 是否显示预习资料与章节
      isHandleSuccess: false  // 是否通过 驳回
    };
  },
  mounted() {
    this.capitalizeNumObj(); //获取阿拉伯数字对应的汉字
    this.courseLevel(); //获取课程等级
    this.getCourseTypes();
    // this.getGabbage();
    this.courseId = this.$route.query.id;
    this.originPath = this.$route.query.originPath;
    this.isCheck =
      this.originPath == "/exper/views/operation/courseAudit" ||
      this.originPath == "/home";
    this.alreadyCheck = this.$route.query.alreadyCheck;
    if (this.courseId) {
      this.getApplyDetail();
    }
  },
  computed: {
    isDisable() {
      return (
        (this.baseInfoForm.auditStatus == 1 &&
          this.baseInfoForm.courseStatus == 1) ||
        (this.baseInfoForm.auditStatus == 0 &&
          this.baseInfoForm.courseStatus == 1)
      );
    },
  },
  watch: {},
  methods: {
    startDate() {
      const self = this;
      return {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      };
    },
    endDate() {
      const self = this;
      return {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      };
    },
    downLoadFile(it) {
      teacherApi.downloadFile(it.fileName, it);
      // window.open(this.host +it.filePath)
    },
    async getApplyDetail() {
      let { data } = await teacherApi.getDetail({ id: this.courseId });
      this.data = data.courseSyllabusTree || [];
      this.baseInfoForm = data.courseInfo;
      this.preList = data.preDataList;
      // this.homePng = await operateApi.viewUrl(this.baseInfoForm.homePage);
    },
    // 审核驳回
    async check(value) {
      let data = await operateApi.check({ id: this.courseId, state: value });
      if ((this.data = 10200)) {
        this.$message.success("操作成功");
        this.isHandleSuccess = true
      }
    },
    async courseLevel() {
      let { data } = await teacherApi.courseLevel();
      this.difficultyList = data;
    },
    async getCourseTypes() {
      let { data } = await teacherApi.getCourseTypes();
      this.courseTypeList = data;
    },
    onSubmit(value) {
      if (
        new Date(Date.parse(this.baseInfoForm.endTime)) >
        new Date(Date.parse(this.baseInfoForm.startTime))
      ) {
        this.$refs["baseInfoForm"].validate(async valid => {
          if (valid) {
            // 编辑
            let obj = {
              course: { ...this.baseInfoForm, id: this.courseId },
              courseSyllabus: {},
              courseSyllabusFile: {},
              operateType: value,
            };
            if (!this.courseId) {
              // 新增
              let data = await teacherApi.jxCourse(obj);
              if (data.code == 10200) {
                this.baseInfoForm = data.data;
                this.$message.success(data.msg);
                this.isShow = true
                if (value == 'submit') {
                  this.$router.push('/exper/views/teacher/courseApply')
                }
              } else {
                this.$message.error(data.msg);
              }
              this.courseId = data.data.id;
            } else {
              // 编辑
              let data = await teacherApi.updateCourse(obj);
              if (data.code == 10200) {
                this.$message.success(data.msg);
                if (value == 'submit') {
                  this.$router.push('/exper/views/teacher/courseApply')
                }
              } else {
                this.$message.error(data.msg);
              }
            }
          } else {
            return false;
          }
        });
      } else {
        this.$message.info("结束时间必须晚于开始时间");
      }
    },
    // 有关上传内容
    handleChange(file, fileList) {
      if (this.$funUtil.checkImg(file)) {
        this.fileList = fileList.slice(-1);
        this.uploadFile(file);
      } else {
        this.fileList = [];
      }
    },
    async uploadFile(file) {
      let formData = new FormData();
      formData.append("file", file.raw);
      let { data } = await teacherApi.fileUpload(formData);
      this.baseInfoForm.homeName = data.data.fileName;
      this.baseInfoForm.homePage = data.data.url;
      // this.homePng = await operateApi.viewUrl(data.data.fileName);
      this.homePng = data.data.url;
    },
    handleRemove(file, fileList) {
      this.fileList = fileList.slice(-1);
      if (this.baseInfoForm.homePage) {
        teacherApi.deleteFile(_this.baseInfoForm.homePage).then(data => {
          if (data.code == 10200) {
            this.$message({
              type: "success",
              message: "删除附件成功",
            });
            this.baseInfoForm.homePage = "";
          }
        });
      }
    },
    // 有关上传内容
    handleChangePre(file, fileList) {
      // this.preList = fileList.slice(-1);
      this.uploadFilePre(file);
    },
    async uploadFilePre(file) {
      let formData = new FormData();
      formData.append("file", file.raw);
      let { data } = await teacherApi.fileUpload(formData);
      this.baseInfoForm.preDataPath = data.data.originalFileName;

      this.addPreDataFiles(data.data);
    },
    async addPreDataFiles(res) {
      let data = await teacherApi.addPreDataFiles({
        courseId: this.courseId,
        fileName: res.originalFileName,
        filePath: res.url,
      });
      if (data.code == 10200) {
        data.data.forEach(it => {
          it.name = it.fileName;
          it.url = it.filePath;
        });
        this.preList = data.data;
        this.$message.success("上传附件成功");
      }
    },
    // 上传前的校验
    handleBeforeUploadPre(file) {},
    handleRemovePre(file, fileList) {},
    async deleteFile(obj) {
      let data = await teacherApi.deleteFile(obj.fileName);
      if (data.code == 10200) {
        let res = await teacherApi.removePreDataFile({
          courseId: this.courseId,
          id: obj.id,
        });
        res.data.forEach(it => {
          it.name = it.fileName;
          it.url = it.filePath;
        });
        this.preList = res.data;
        this.$message.success("删除附件成功");
      }
    },
    //新增一级目录模块点击事件
    handleNewMoudle() {
      let length = this.data.length + 1;
      this.data.push({
        label: `第${numtoCh[length]}章`,
        children: [],
        isEdit: true,
        pid: 0,
      });
      this.$nextTick(() => {
        if (this.$refs["slotTreeInput"]) {
          this.$refs["slotTreeInput"].$refs.input.focus();
        }
      });
    },
    //新增按钮
    append(node, data) {
      let length = data.children.length + 1;
      // console.log(node, data, );
      if (node.level >= this.MAX_LEVEL) {
        this.$message.warning(
          "当前目录已达到" + this.MAX_LEVEL + "级,无法新增！"
        );
        return false;
      }
      //新定义一个对象
      const newChild = {
        // id: id++,
        label: `第${numtoCh[length]}节`,
        children: [],
        isEdit: true,
        pid: data.id,
      };
      if (!data.children) {
        this.$set(data, "children", []);
      }
      data.children.push(newChild);
      //新增子节点到2级
      this.$nextTick(() => {
        // if (this.$refs["slotTreeInput" + data[this.id]]) {
        //   this.$refs["slotTreeInput" + data[this.id]].$refs.input.focus();
        // }
        if (this.$refs["slotTreeInput"]) {
          this.$refs["slotTreeInput"].$refs.input.focus();
        }
      });
    },

    handleEdit(node, data) {
      // console.log(data, "dddd");
      // 编辑节点
      // 设置编辑状态
      if (!data.isEdit) {
        this.$set(data, "isEdit", true);
      }
      // 输入框聚焦
      this.$nextTick(() => {
        if (this.$refs["slotTreeInput"]) {
          this.$refs["slotTreeInput"].$refs.input.focus();
        }
      });
    },
    //删除按钮
    remove(node, data) {
      this.$confirm("确定要删除吗", "提示", {
        confirmButtonText: "确定",
        type: "warning",
        center: true,
      }).then(async () => {
        let res = await teacherApi.deleteSyllabusNode({
          id: data.id,
          courseId: this.courseId,
        });
        this.data = res.data;
      });
    },
    //退出编辑按钮
    async handleInput(node, data) {
      // 退出编辑，如果有id，则是编辑，否则是新增
      let obj = { ...data, courseId: this.courseId };
      let res = data.id
        ? await teacherApi.upateSyllabusNode(obj)
        : await teacherApi.addSyllabusNode(obj);
      this.data = res.data;
      // 退出编辑状态
      if (data.isEdit) {
        this.$set(data, "isEdit", false);
      }
    },
    // 阿拉伯数字转化为大写的一，二，三
    capitalizeNumObj() {
      let obj = {};
      // 暂定100章，可改动
      for (let i = 1; i < 100; i++) {
        obj[i] = this.$funUtil.capitalizeNum(i);
      }
      numtoCh = obj;
    },
  },
  created() {},
};
</script>
<style lang="less" scoped>
.courseApply {
  /deep/.el-upload-list .el-upload-list--text {
    width: 50% !important;
  }
}
.avatar-uploader {
  width: 30%;
}
.custom-tree-container {
  /deep/.el-tree-node {
    margin-bottom: 25px;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.el-tree {
  height: 100%;
  .isEdit {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .el-input {
      width: 100px;
      height: 5px;
    }
  }
}
.el-icon-plus {
  margin: 10px 0 0 22px;
  // color: #606266;
  font-size: 14px;
  span {
    margin-left: 10px;
    font-size: 14px;
  }
}
.textAreaBox{
  width: 99%;
  margin-left: 1%;
}
.handleBtn{
  margin-right: 10px;
}
</style>
<style lang="less">
.courseApply .el-tree{
  padding: 20px;
border: 1px solid rgb(192, 196, 204)
}
</style>
